package org.mao.parser;

import java.net.SocketTimeoutException;
import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.mao.forum.dao.ForumPostDao;
import org.mao.forum.dao.ForumPostImageDao;
import org.mao.forum.entity.ForumPost;
import org.mao.forum.entity.ForumPostImage;
import org.mao.forum.vo.ForumTaskParamsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;

@Service("SisForumPageParser")
public class SisForumPageParser extends BaseForumParser implements IForumPageParser {

	private static Logger logger = Logger.getLogger(SisForumPageParser.class);

	@Autowired
	private ForumPostDao forumPostDao;

	@Autowired
	private ForumPostImageDao forumPostImageDao;

	// 根据一个板块，列出要读的每页的url
	@Override
	public List<String> readSectionList(Integer sectionId, ForumTaskParamsVo paramsVo) {
		return super.readSectionList(sectionId, paramsVo);
	}

	// 读某板块的一页上所有的帖子url
	@Override
	public List<ForumPost> readSisPostList(String sectionUrl, Integer sectionId) {
		List<ForumPost> postList = Lists.newArrayList();
		try {
			Document doc = Jsoup.connect(sectionUrl).get();
			Elements eles = doc.getElementsContainingText("版块主题");
			Element table = null;
			for (Element ele : eles) {
				if (ele.tagName().toLowerCase().equals("table")) {
					table = ele;
					break;
				}
			}
			if (table != null) {
				Elements tbodys = table.select("tbody");
				for (Element tbody : tbodys) {
					Elements ths = tbody.select("tr>th");
					if (ths.size() > 0) {
						Elements links = ths.get(0).select("a");
						if (links.size() > 1) {
							Element link = links.get(1);
							String postNumber = tbody.attr("id");
							String url = link.attr("abs:href");
							String postName = link.text();

							ForumPost forumPost = super.initForumPost(postNumber, postName, sectionId, url);
							if (forumPost.getId() == null) {
								postList.add(forumPost);
							}
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return postList;
	}

	// 读取某帖子的信息
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void readPost(ForumPost forumPost) {
		try {
			logger.info("read post url:" + forumPost.getUrl());
			Document postDoc = Jsoup.connect(forumPost.getUrl()).get();
			Date now = new Date();
			if (forumPost.getId() == null) {
				this.readAttarch(postDoc, forumPost);
				forumPost.setTorrentDownload(0);
				forumPost.setValid(1);
				forumPost.setCreateTime(now);
				List<String> imageUrlList = this.readImageList(postDoc, forumPost);
				forumPostDao.insert(forumPost);

				for (String imageUrl : imageUrlList) {
					ForumPostImage forumPostImage = new ForumPostImage();
					forumPostImage.setPostId(forumPost.getId());
					forumPostImage.setHasDownload(0);
					forumPostImage.setUrl(imageUrl);
					forumPostImage.setCreateTime(now);
					forumPostImageDao.insert(forumPostImage);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	// 读取帖子上的附件信息
	@Override
	public void readAttarch(ForumPost forumPost) {
		try {
			Document postDoc = Jsoup.connect(forumPost.getUrl()).timeout(5000).get();
			this.readAttarch(postDoc, forumPost);
		} catch (SocketTimeoutException se) {
			forumPost.setTorrentName("Read timed out");
		} catch (Exception e) {
			logger.error("", e);
		}
	}
	
	// 读取某帖子的图片
	@Override
	public List<String> readImageList(ForumPost forumPost) {
		try {
			Document postDoc = Jsoup.connect(forumPost.getUrl()).get();
			return this.readImageList(postDoc, forumPost);
		} catch (Exception e) {
			logger.error("", e);
		}
		return Lists.newArrayList();
	}

	// 读取帖子上的附件信息
	private void readAttarch(Document doc, ForumPost forumPost) {
		try {
			Elements forms = doc.getElementsByTag("form");
			if (forms.size() > 0) {
				Element form = forms.get(0);
				Elements tables = form.select(">div>table");
				if (tables.size() > 0) {
					Element table = tables.get(0);
					// <dl class="t_attachlist">
					Elements linkItems = table.select("dl[class='t_attachlist']>dt>a");
					if (CollectionUtils.isNotEmpty(linkItems)) {
						for (Element link : linkItems) {
							if (link.text().endsWith("torrent")) {
								String torrentName = link.text().trim();
								String torrentUrl = link.attr("abs:href").trim();
								forumPost.setTorrentName(torrentName);
								forumPost.setTorrentUrl(torrentUrl);
							}
						}
					} else {
						forumPost.setTorrentName("torrent link not found");
					}
				}
			}
		} catch (Exception e) {
			logger.error("", e);
			forumPost.setTorrentName("torrent link not found");
		}
	}

	private List<String> readImageList(Document doc, ForumPost forumPost) {
		List<String> imageUrlList = Lists.newArrayList();
		try {
			Elements forms = doc.getElementsByTag("form");
			if (forms.size() > 0) {
				Element form = forms.get(0);
				Elements tables = form.select(">div>table");
				if (tables.size() > 0) {
					Element table = tables.get(0);
					Elements divItems = table.select("div[class='t_msgfont']");
					if (divItems.size() > 0) {
						Element divItem = divItems.get(0);
						String text = divItem.text();
						text = text.replace("【", "\r\n【");
						text = text.trim();
						forumPost.setContent(text);
						// logger.info("post title: "+text);
						// System.out.println(text);
						Elements images = divItem.select("img");
						for (Element image : images) {
							String imageUrl = image.attr("abs:src");
							imageUrlList.add(imageUrl);
						}
					}
				}

			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return imageUrlList;
	}
}
